<template>
  <div class="incoming-inspection-list-page">
    <div class="card-stack">
      <el-card class="card-block breadcrumb-card">
        <el-breadcrumb :separator-icon="ArrowRight">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>质量管理</el-breadcrumb-item>
          <el-breadcrumb-item>来料检验</el-breadcrumb-item>
          <el-breadcrumb-item>来料检验列表</el-breadcrumb-item>
        </el-breadcrumb>
      </el-card>

      <el-card class="card-block query-card">
        <el-form class="filter-form" :inline="true" :model="queryForm" label-width="auto">
          <el-form-item label="检验单">
            <el-input
              v-model="queryForm.keyword"
              placeholder="请输入检验单编号/名称"
              clearable
              style="width: 240px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="物料">
            <el-select
              v-model="queryForm.materialId"
              placeholder="请选择物料"
              filterable
              remote
              clearable
              reserve-keyword
              :remote-method="fetchMaterialOptions"
              :loading="materialSelectLoading"
              style="width: 220px"
            >
              <el-option
                v-for="item in materialOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <div class="option-line">
                  <span class="option-name">{{ item.label }}</span>
                  <span class="option-code">{{ item.code }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检验部门">
            <el-tree-select
              v-model="queryForm.departmentId"
              :data="departmentTree"
              placeholder="请选择检验部门"
              check-strictly
              clearable
              filterable
              style="width: 220px"
            />
          </el-form-item>
          <el-form-item label="检验人员">
            <el-select
              v-model="queryForm.inspectorId"
              placeholder="请选择质检人员"
              clearable
              filterable
              :loading="inspectorLoading"
              :disabled="!queryForm.departmentId"
              style="width: 200px"
            >
              <el-option
                v-for="item in inspectorOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <el-card class="card-block table-card">
        <div class="table-toolbar">
          <div class="left-actions">
            <el-button type="primary" @click="handleCreate">新增</el-button>
            <el-button type="danger" plain :disabled="!multipleSelection.length" @click="handleBatchDelete">
              删除
            </el-button>
          </div>
          <div class="table-total">共 {{ pagination.totalCount }} 条</div>
        </div>
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          :max-height="560"
          :loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" fixed="left" />
          <el-table-column type="index" label="序号" width="70" fixed="left">
            <template #default="{ $index }">
              {{ (pagination.pageIndex - 1) * pagination.pageSize + $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="inspectionname" label="检验单名称" min-width="160" fixed="left" />
          <el-table-column prop="inspectioncode" label="检验单号" min-width="150" fixed="left" />
          <el-table-column prop="materialname" label="物料名称" min-width="140" />
          <el-table-column prop="materialcode" label="物料编号" min-width="140" />
          <el-table-column prop="specification" label="规格型号" min-width="120" />
          <el-table-column prop="unit" label="单位" width="70" />
          <el-table-column prop="batchno" label="批次号" min-width="120" />
          <el-table-column prop="incomingdate" label="来料日期" min-width="140" />
          <el-table-column prop="inspectiondate" label="检验日期" min-width="140" />
          <el-table-column prop="departmentname" label="检验部门" min-width="140" />
          <el-table-column prop="inspectornames" label="检验人" min-width="140" />
          <el-table-column prop="inspectionqty" label="检测数量" width="110" align="right" />
          <el-table-column prop="qualifiedqty" label="合格数量" width="110" align="right" />
          <el-table-column prop="unqualifiedqty" label="不合格数量" width="120" align="right" />
          <el-table-column label="检验结果" width="110">
            <template #default="{ row }">
              <el-tag :type="row.inspectionresult === '合格' ? 'success' : 'danger'">
                {{ row.inspectionresult || '-' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="180" show-overflow-tooltip />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            v-model:current-page="pagination.pageIndex"
            v-model:page-size="pagination.pageSize"
            :total="pagination.totalCount"
            :page-sizes="[10, 20, 30, 50]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ArrowRight, Search } from '@element-plus/icons-vue'
import { onMounted, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import https from '@/Http/http'
import { ElMessage, ElMessageBox } from 'element-plus'

type ApiEnum = -1 | 0 | 1

interface ApiPageingResponse<T> {
  code: ApiEnum
  msg: string
  data: T[]
  totalCount: number
  pageCount: number
}

interface ApiResultResponse<T> {
  code: ApiEnum
  msg: string
  data: T
}

interface IncomingInspectionDTO {
  id: number
  inspectioncode: string
  inspectionname: string
  incomingdate?: string
  inspectiondate?: string
  departmentname?: string
  departmentid?: number
  inspectornames?: string
  inspectionqty?: number
  qualifiedqty?: number
  unqualifiedqty?: number
  inspectionresult?: string
  remark?: string
  batchno?: string
  materialname?: string
  materialcode?: string
  specification?: string
  unit?: string
}

interface MaterialOption {
  label: string
  value: number
  code: string
}

interface MaterialDTO {
  id: number
  materialcard: string
  materialname: string
  materialunit?: string
  materialmodelsame?: string
}

interface DepartmentNode {
  label: string
  value: number
  children?: DepartmentNode[]
}

interface InspectorOption {
  label: string
  value: number
}

const router = useRouter()
const loading = ref(false)
const tableData = ref<IncomingInspectionDTO[]>([])
const multipleSelection = ref<IncomingInspectionDTO[]>([])

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0
})

const queryForm = reactive({
  keyword: '',
  materialId: undefined as number | undefined,
  departmentId: undefined as number | undefined,
  inspectorId: undefined as number | undefined
})

const materialOptions = ref<MaterialOption[]>([])
const materialSelectLoading = ref(false)
const departmentTree = ref<DepartmentNode[]>([])
const inspectorOptions = ref<InspectorOption[]>([])
const inspectorLoading = ref(false)

const fetchMaterialOptions = async (keyword = '') => {
  materialSelectLoading.value = true
  try {
    const params: Record<string, any> = {
      pageindex: 1,
      pagesize: 30
    }
    if (keyword) {
      params.materialname = keyword
    }
    const { data } = await https.Reads.get<ApiPageingResponse<MaterialDTO>>('/Material/MaterialGetList', {
      params
    })
    if (data.code === 1) {
      materialOptions.value = (data.data || []).map((item) => ({
        label: item.materialname,
        value: item.id,
        code: item.materialcard
      }))
    }
  } catch (error) {
    console.error('获取物料列表失败', error)
  } finally {
    materialSelectLoading.value = false
  }
}

const fetchDepartmentTree = async () => {
  try {
    const { data } = await https.Reads.get<ApiResultResponse<DepartmentNode[]>>('/Organtion/Binds')
    if (data.code === 1) {
      departmentTree.value = data.data || []
    }
  } catch (error) {
    console.error('获取部门树失败', error)
  }
}

const fetchInspectorOptions = async (organId: number) => {
  inspectorLoading.value = true
  try {
    const { data } = await https.Reads.get<ApiResultResponse<any[]>>('/RBAC/ShowOrganUser', {
      params: { organid: organId }
    })
    if (data.code === 1) {
      inspectorOptions.value = (data.data || [])
        .map((item) => ({
          label: item.userName ?? item.UserName ?? item.username ?? '',
          value: item.userId ?? item.UserId ?? item.id
        }))
        .filter((item) => item.label && item.value)
    } else {
      inspectorOptions.value = []
    }
  } catch (error) {
    console.error('获取人员失败', error)
    inspectorOptions.value = []
  } finally {
    inspectorLoading.value = false
  }
}

watch(
  () => queryForm.departmentId,
  (val) => {
    queryForm.inspectorId = undefined
    inspectorOptions.value = []
    if (val !== undefined && val !== null) {
      fetchInspectorOptions(val)
    }
  }
)

const fetchTableData = async () => {
  loading.value = true
  try {
    const params: Record<string, any> = {
      pageindex: pagination.pageIndex,
      pagesize: pagination.pageSize
    }
    if (queryForm.keyword) params.keyword = queryForm.keyword
    if (queryForm.materialId) params.materialid = queryForm.materialId
    if (queryForm.departmentId) params.departmentid = queryForm.departmentId
    if (queryForm.inspectorId) params.inspectorid = queryForm.inspectorId

    const { data } = await https.Reads.get<ApiPageingResponse<IncomingInspectionDTO>>(
      '/IncomingInspection/List',
      { params }
    )
    if (data.code !== 1) {
      throw new Error(data.msg || '查询失败')
    }
    pagination.totalCount = data.totalCount || 0
    tableData.value = data.data || []
  } catch (error: any) {
    console.error('获取来料检验列表失败', error)
    if (error.response?.status === 404) {
      ElMessage.error('读取接口不存在，请确认后端服务已启动')
    } else {
      ElMessage.error(error.message || '获取来料检验列表失败')
    }
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  pagination.pageIndex = 1
  fetchTableData()
}

const handleReset = () => {
  queryForm.keyword = ''
  queryForm.materialId = undefined
  queryForm.departmentId = undefined
  queryForm.inspectorId = undefined
  fetchMaterialOptions()
  fetchTableData()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchTableData()
}

const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  fetchTableData()
}

const handleSelectionChange = (rows: IncomingInspectionDTO[]) => {
  multipleSelection.value = rows
}

const handleCreate = () => {
  router.push('/IncomingInspectionAdd')
}

const handleEdit = (row: IncomingInspectionDTO) => {
  router.push({
    path: '/IncomingInspectionAdd',
    query: { id: row.id?.toString() }
  })
}

const deleteIncomingInspection = (id: number) =>
  https.Writes.request<ApiResultResponse<number>>({
    method: 'delete',
    url: '/Detection/IncomingInspectionDelete',
    params: { id }
  })

const handleDelete = (row: IncomingInspectionDTO) => {
  ElMessageBox.confirm(`确认删除检验单【${row.inspectionname}】吗？`, '提示', {
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await deleteIncomingInspection(row.id)
        if (res.data.code !== 1) {
          throw new Error(res.data.msg || '删除失败')
        }
        ElMessage.success('删除成功')
        fetchTableData()
      } catch (error: any) {
        console.error(error)
        ElMessage.error(error.message || '删除失败')
      }
    })
    .catch(() => {})
}

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) return
  ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 条检验单吗？`, '提示', {
    type: 'warning'
  })
    .then(async () => {
      try {
        await Promise.all(multipleSelection.value.map((item) => deleteIncomingInspection(item.id)))
        ElMessage.success('批量删除成功')
        fetchTableData()
      } catch (error: any) {
        console.error(error)
        ElMessage.error(error.message || '批量删除失败')
      }
    })
    .catch(() => {})
}

onMounted(() => {
  fetchTableData()
  fetchMaterialOptions()
  fetchDepartmentTree()
})
</script>

<style scoped>
.incoming-inspection-list-page {
  min-height: calc(100vh - 60px);
  padding: 16px;
  background: linear-gradient(135deg, #f3f5ff 0%, #fef5f5 45%, #fdf8ff 100%);
}

.card-stack {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.card-block {
  width: 100%;
  background: linear-gradient(145deg, rgba(255, 255, 255, 0.92), rgba(242, 248, 255, 0.85));
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.6);
  box-shadow: 0 10px 30px rgba(15, 36, 70, 0.08);
}

.query-card {
  padding-bottom: 4px;
}

.filter-form :deep(.el-form-item) {
  margin-bottom: 10px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.left-actions {
  display: flex;
  gap: 12px;
}

.table-total {
  color: #909399;
}

.option-line {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.option-name {
  font-weight: 500;
}

.option-code {
  color: #909399;
  font-size: 12px;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>

